<template>
  <div>
    <avue-form
      ref="form"
      v-model="form"
      :class="['afd-preview-form', cusDetail && 'cusDetail', outClass]"
      :option="options"
      :upload-after="uploadAfter"
      :upload-preview="uploadPreview"
      @submit="handlePreviewSubmit"
    >
      <template v-slot:cusimg="scope">
        <avueCusImg :params="scope.column.params" />
      </template>
      <template v-slot:cusarray="scope">
        <div v-for="(it, index) in computedFormData(scope.column)" :key="index" class="array-item">
          <el-tooltip v-if="scope.column.type === 'url'" effect="dark" :content="it" placement="top">
            <div style="width: 100%;">{{ it }}</div>
            <template v-slot:content>
              <el-link :href="it" target="_self" type="primary">{{ it }}</el-link>
            </template>
          </el-tooltip>
          <span v-else>{{ it }}</span>
        </div>
      </template>
      <template v-slot:cusstring="scope">
        <div class="array-item">
          {{ computedFormData(scope.column) }}
        </div>
      </template>
    </avue-form>
    <el-image-viewer
      v-if="imgViewerVisible"
      :on-close="closeImgViewer"
      :url-list="previewList"
      style="z-index: 9999"
    />
  </div>
</template>
<script>
  import { getToken } from '@/utils/auth'
  import previewMixin from '@/mixin/previewMixin'
  import { isAssetTypeAnImage } from '@/utils/index'
  import avueCusImg from './avueCusImg'
  import { validatenull } from '../utils/index'
  export default {
    name: 'GenerateForm', // 预览图片混入
    components: { avueCusImg },
    mixins: [previewMixin],
    props: {
      option: {
        type: Object,
        default: () => {
          return {}
        },
      },
      value: {
        type: Object,
        default: () => {
          return {}
        },
      },
      busSubType: {
        type: Number,
        default: 3012
      },
      add: {
        type: Boolean,
        default: true
      },
      outClass: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        token: getToken(),
        cusDetail: false,
        imgViewerVisible: false,
        previewList: [],
        cloneOption: {},
        form: {},
        defaultValue: {},
        options: {}
      }
    },
    computed: {
      // 计算表单值
      computedFormData() {
        return function(column) {
          const val = this.form[column._prop]
          return val || ''
        }
      }
    },
    watch: {
      option: {
        handler(val) {
          const isStr = typeof val === 'string'
          if (isStr) {
            this.cloneOption = JSON.parse(val)
          } else {
            this.cloneOption = JSON.parse(JSON.stringify(val || {}))
          }
          this.refreshOption()
          this.refreshStyle()
        },
        immediate: true,
        deep: true,
      },
      value: {
        handler(val) {
          const _val = val ? JSON.parse(JSON.stringify(val)) : {}
          this.form = Object.assign(this.defaultValue, _val)
          this.refreshStyle()
        },
        deep: true,
        immediate: true
      },
    },
    methods: {
      refreshStyle() {
        this.$nextTick(() => {
          const conClass = this.outClass ? `.${this.outClass}.afd-preview-form` : '.afd-preview-form'
          if (this.options.gutter) {
            // 分组标题兼容gutter属性
            const groupTitleArr = document.querySelectorAll(conClass + ' .el-collapse-item__header')
            for (const val of groupTitleArr) {
              const pd = Math.floor(this.options.gutter / 2)
              val.style.paddingLeft = pd + 'px'
              val.style.paddingRight = pd + 'px'
            }
          }
          // 富文本兼容导出高度
          const groupTitleArr = document.querySelectorAll(conClass + ' .w-e-text-container')
            for (const val of groupTitleArr) {
              if (this.cusDetail) {
                val.style.height = 'unset'
                val.style.minHeight = '80px'
              } else {
                val.style.height = 300
              }
            }
          // 富文本兼容导出高度
          const htmlArr = document.querySelectorAll(conClass + ' .wangEditor_html')
          for (const val of htmlArr) {
            val.parentNode.style.display = 'none'
          }

          // 富文本待办详情模式不可点击
          const checkboxArr = document.querySelectorAll(conClass + ' .avue-ueditor input')
          console.log(this.cusDetail, 'this.cusDetail')
          for (const val of checkboxArr) {
            if (this.cusDetail) {
              val.setAttribute('disabled', true)
            } else {
              val.removeAttribute('disabled')
            }
          }
        })
      },
      refreshOption() {
        if (this.cloneOption.detail) {
          this.cloneOption.cusDetail = true
        }
        // 查看模式转自定义详情模式
        this.cusDetail = !!this.cloneOption.cusDetail
        if (this.cloneOption.cusDetail) {
          // readonly模式样式bug太多,转为disabled模式
          this.cloneOption.readonly = false
          this.cloneOption.detail = false
          this.cloneOption.disabled = true
        } else if (this.cloneOption.disabled) {
          this.cloneOption.readonly = false
          this.cloneOption.detail = false
        }
        // 标签后缀设置为空无效
        if (!this.cloneOption.labelSuffix) {
          this.cloneOption.labelSuffix = ' '
        }
        this.cloneOption.menuBtn = false
        this.formatOptions()
      },
      formatOptions() {
        this.formatColumn(this.cloneOption.column)
        const group = this.cloneOption.group || []
        group.map((item) => {
          this.formatColumn(item.column)
        })
        this.options = this.cloneOption
        this.form = {
          ...this.defaultValue,
          ...this.form,
        }
      },
      formatColumn(columns, parent) {
        if (!columns || !columns.length) return
        for (const val of columns) {
          val._prop = val.prop
          if (this.add && !validatenull(val.value)) {
            // 收集默认值
            this.$set(this.defaultValue, val.prop, val.value)
          }
          if (this.cusDetail) {
            // 详情不显示占位内容
            this.$set(val, 'placeholder', ' ')
            val.startPlaceholder = ' '
            val.endPlaceholder = ' '
            val.customConfig ||= {}
            val.customConfig.placeholder = ' '
          }
          if (val.type === 'cusimg') {
            val.prop = 'cusimg'
          } else if (val.type === 'title') {
            this.$set(this.defaultValue, val.prop, val.value)
          } else if (['upload'].includes(val.type)) {
            val.headers ||= {}
            val.data ||= {}
            val.headers.Authorization = this.token
            val.data.busSubType = this.busSubType
          } else if (['ueditor'].includes(val.type)) {
            val.customConfig ||= {}
            val.customConfig.height = 300
            if (this.value[val._prop]) {
              val.customConfig.placeholder = ' '
            }
          } else if (val.type === 'dynamic') {
            this.formatColumn(val.children?.column, val)
          } else if (['textarea', 'input', 'color'].includes(val.type)) {
            // 兼容多行文本导出bug
            if (this.cusDetail) {
              this.$set(val, 'styles', {
                color: '#606266',
                fontSize: '14px',
                fontWeight: 'normal',
                lineHeight: 1.6,
                border: '1px solid #DCDFE6',
                borderRadius: '4px',
                padding: '5px 15px',
                margin: 0,
                minHeight: val.type === 'textarea' ? '64px' : '32px',
                wordBreak: 'break-all',
                whiteSpace: 'pre-wrap',
              })
              this.$set(val, 'type', 'title')
            }
          } else if (['url', 'array'].includes(val.type)) {
            // 兼容详情换行
            if (this.cusDetail && !parent) {
              val.prop = `cusarray`
            }
          }
        }
      },
      handlePreviewSubmit(form, done) {
        done()
      },
      uploadAfter(res, done, loading) {
        res.data = {
          fileId: res.fileId,
          fileName: res.fileName,
        }
        done()
      },
      // 文件预览
      uploadPreview(file, column, done) {
        console.log(file, '这是file')
        // 获取最后一个.的位置
        const index = file.name.lastIndexOf('.')
        // 获取后缀
        const ext = file.name.substr(index + 1)

        if (isAssetTypeAnImage(ext)) {
          this.imgViewerVisible = true
          if (!file.previewUrl) {
            file.previewUrl =
              process.env.VUE_APP_BASE_API +
              `/storage-service/file/image?fileId=${file.url}&token=${this.token}`
          }
          this.previewList = [file.previewUrl]
          const m = (e) => {
            e.preventDefault()
          }
          document.body.style.overflow = 'hidden'
          document.addEventListener('touchmove', m, false) // 禁止页面滑动
        } else {
          this.downloadFile(file)
        }
      },
      // 下载文件
      downloadFile(file) {
        this.$apis.file.dwlFile(file.url, file.name)
      },
      // 校验表单
      validate() {
        return new Promise((res, rej) => {
          this.$refs.form.validate((isValid, done) => {
            done()
            if (isValid) {
              res(this.form)
            } else {
              rej()
            }
          })
        })
      },
    },
  }
</script>
<style lang="less" scoped>
  ::v-deep .avue-time .el-range-editor--small {
    .el-range-separator,
    .el-range__icon {
      line-height: 32px !important;
    }
  }
  .afd-preview-form {
    overflow: hidden;
    ::v-deep.el-form {
      .el-form-item {
        background: #fff;
        margin-bottom: 24px;
        .el-form-item__content {
          line-height: 32px;
        }
        .el-radio__label,.el-checkbox__label {
          color: #48505b!important;
        }
      }
      .el-table .el-form-item {
        margin-bottom: 0px !important;
        .el-form-item__content {
          line-height: normal;
        }
      }
      .el-form-item__label {
        color: #48505B;
      }
      .el-textarea__inner {
        resize: display;
      }
      .avue-group__title {
        font-weight: 700;
      }
      .avue-array__input {
        display: flex;
        align-items: center;
      }
      .el-date-editor {
        min-width: unset;
      }
      .w-e-text-container {
        ul li {
          list-style: disc;
        }
        ol li {
          list-style: decimal;
        }
        ul.w-e-todo,ol.w-e-todo {
          li {
            list-style: none;
          }
        }
      }
    }
    &.cusDetail {
      ::v-deep.el-form {
        .el-input__inner,
        .el-textarea__inner,
        .el-date-editor,
        .el-range-input {
          background-color: #fff;
          color: #606266;
        }
        .w-e-menu {
          display: none;
        }
        .el-radio__input.is-checked.is-disabled .el-radio__inner {
          display: flex;
          justify-content: center;
          align-items: center;
          &::after {
            transform: none;
            position: static;
          }
        }
      }
    }
    .array-item {
      color: #606266;
      font-size: 14px;
      font-weight: normal;
      line-height: 1.6;
      border: 1px solid #DCDFE6;
      border-radius: 4px;
      padding: 5px 15px;
      margin-bottom: 8px;
      min-height: 32px;
      word-break: break-all;
      display: flex;
      align-items: center;
    }
    ::v-deep.el-button.is-circle {
      display: none;
      width: 22px;
      height: 22px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  ::v-deep .avue-form__item--right .el-form-item__label {
    text-align: right !important;
  }
</style>
